package com.bw.module_cinema.search

import android.app.ProgressDialog
import android.content.DialogInterface
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.widget.EditText
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bw.lib_storage.db.DBUtils
import com.bw.lib_storage.db.entity.SearchEntity
import com.bw.module_cinema.R
import com.bw.module_cinema.model.api.CinemaApi
import com.google.android.flexbox.FlexboxLayoutManager
import com.google.android.flexbox.JustifyContent
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import javax.inject.Inject

@AndroidEntryPoint
class SearchActivity : AppCompatActivity() {

    //通过 Hilt 自动注入CinemaApi实例（网络请求接口）
    @Inject lateinit var cinemaApi: CinemaApi

    private lateinit var adapter: SearchResultAdapter
    private lateinit var historyAdapter: SearchHistoryAdapter

    //协程 Job 对象，用于管理防抖逻辑（取消未执行的搜索请求）。
    private var debounceJob: Job? = null

    private val searchDao by lazy {
        DBUtils.getDB().searchDao()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_search)

        val et = findViewById<EditText>(R.id.et_keyword)
        val clear = findViewById<ImageView>(R.id.iv_clear)
        val rv = findViewById<RecyclerView>(R.id.rv_results)
        val rvHistory = findViewById<RecyclerView>(R.id.rv_history)
        val llHistory = findViewById<LinearLayout>(R.id.ll_history)
        val clearHistory = findViewById<ImageView>(R.id.iv_clear_history)

        // 初始化搜索结果适配器
        adapter = SearchResultAdapter()
        rv.layoutManager = LinearLayoutManager(this)
        rv.adapter = adapter

        // 初始化搜索历史适配器

        historyAdapter = SearchHistoryAdapter()
        //流式布局
        val flexLayoutManager = FlexboxLayoutManager(this)
        flexLayoutManager.justifyContent = JustifyContent.FLEX_START
        rvHistory.layoutManager = flexLayoutManager
        rvHistory.adapter = historyAdapter

        // 设置历史记录点击监听器
        historyAdapter.setOnItemClickListener(object : SearchHistoryAdapter.OnItemClickListener {
            override fun onItemClick(entity: SearchEntity) {
                // 点击历史记录项，填充到搜索框并执行搜索
                et.setText(entity.title)
                et.setSelection(entity.title.length)
                performSearch(entity.title)
            }
        })
        
        // 设置历史记录删除监听器
        historyAdapter.setOnDeleteClickListener(object : SearchHistoryAdapter.OnDeleteClickListener {
            override fun onDeleteClick(entity: SearchEntity) {
                // 删除单个历史记录项
                deleteHistoryItem(entity)
            }
        })

        // 清空搜索框按钮
        clear.setOnClickListener {
            et.setText("")
        }

        // 清空历史记录按钮
        clearHistory.setOnClickListener {
            val alertDialog = AlertDialog.Builder(this)
                .setTitle("温馨提示")
                .setMessage("是否清空所有历史记录？")
                .setNegativeButton("取消", null)
                .setPositiveButton("确定") { dialog, which ->
                    clearAllHistory()
                }
                .create()
            alertDialog.show()
        }

        et.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
            override fun afterTextChanged(s: Editable?) {
                val text = s?.toString()?.trim().orEmpty()
                clear.visibility = if (text.isEmpty()) View.GONE else View.VISIBLE
                
                if (text.isEmpty()) {
                    // 文本为空：显示历史记录，隐藏搜索结果
                    rv.visibility = View.GONE
                    llHistory.visibility = View.VISIBLE
                    adapter.setData(emptyList())
                    debounceJob?.cancel()
                    loadSearchHistory()
                } else {
                    // 文本不为空：隐藏历史记录，显示搜索结果
                    llHistory.visibility = View.GONE
                    rv.visibility = View.VISIBLE
                    debounceJob?.cancel()
                    debounceJob = lifecycleScope.launch {
                        delay(300)
                        fetchResults(text)
                    }
                }
            }
        })

        // 页面加载时显示历史记录
        loadSearchHistory()
    }


    private fun saveSearchHistory(keyword: String) {
        if (keyword.isBlank()) return

        lifecycleScope.launch(Dispatchers.IO) {
            try {
                val existing = searchDao.getSearchByExactTitle(keyword)
                if (existing == null) {
                    // 如果不存在，则插入新记录
                    searchDao.insert(SearchEntity(0, keyword))
                }
                // 如果已存在，不重复插入
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    private fun loadSearchHistory() {
        lifecycleScope.launch(Dispatchers.IO) {
            try {
                val historyList = searchDao.getAllSearch().toMutableList().apply { reverse() } // 最新的在前面
                withContext(Dispatchers.Main) {
                    historyAdapter.setData(historyList)
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    private fun clearAllHistory() {
        val progressDialog = ProgressDialog(this).apply {
            setTitle("正在清空历史记录...")
            setCancelable(false)
            show()
        }
        //一次性任务 直接在 Dispatchers.IO 线程执行 deleteAll() 数据库操作，
        // 完成后通过 withContext(Dispatchers.Main) 切换到主线程更新 UI
        lifecycleScope.launch(Dispatchers.IO) {
            try {
                searchDao.deleteAll()
                withContext(Dispatchers.Main) {
                    historyAdapter.setData(emptyList())
                    progressDialog.dismiss()
                    Toast.makeText(this@SearchActivity, "历史记录已清空", Toast.LENGTH_SHORT).show()
                }
            } catch (e: Exception) {
                e.printStackTrace()
                withContext(Dispatchers.Main){
                    progressDialog.dismiss()
                    Toast.makeText(this@SearchActivity, "清空历史记录失败", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

    private fun deleteHistoryItem(entity: SearchEntity) {
        lifecycleScope.launch(Dispatchers.IO) {
            try {
                searchDao.deleteByTitle(entity.title)
                //删除完成后，通过 withContext(Dispatchers.Main) 切换到主线程
                withContext(Dispatchers.Main) {
                    loadSearchHistory() // 重新加载历史记录
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    private fun performSearch(keyword: String) {
        // 保存搜索历史
        saveSearchHistory(keyword)
        // 执行搜索
        fetchResults(keyword)
    }
    private fun fetchResults(keyword: String) {
        lifecycleScope.launch {
            try {
                val resp = cinemaApi.getRecommendSimpleVideo(1, 20)
                val data = resp.data ?: emptyList()
                //从推荐列表中筛选出标题包含搜索关键词的结果，忽略大小写
                val filtered = data.filter { it.title.contains(keyword, ignoreCase = true) }
                adapter.setData(filtered)
                // 搜索完成后保存历史记录
                saveSearchHistory(keyword)
            } catch (_: Exception) {
                //若网络请求失败（如异常），适配器展示空列表，避免崩溃
                adapter.setData(emptyList())
            }
        }
    }
}